# -*- coding: utf-8 -*-
import sys
import ntchat
import time
import requests
import re
import json
import threading
import pika

wechat = ntchat.WeChat()
mq_host = '124.220.182.159'
mq_vhost = 'ceshi_vhost'
mq_queue_name = 'xxsszf'
mq_username = 'ceshi'
mq_password = 'ceshi'
url='http://124.220.182.159:8088'

# 打开pc微信, smart: 是否管理已经登录的微信
wechat.open(smart=True)
#监听消息类型
jtxxlx=(ntchat.MT_RECV_PICTURE_MSG,ntchat.MT_RECV_TEXT_MSG,ntchat.MT_RECV_VOICE_MSG,ntchat.MT_RECV_EMOJI_MSG,ntchat.MT_RECV_REVOKE_MSG,ntchat.MT_ROOM_DEL_NOTIFY_MSG,ntchat.MT_ROOM_DEL_MEMBER_NOTIFY_MSG )
# 注册消息回调
#@wechat.msg_register(ntchat.MT_RECV_TEXT_MSG)
@wechat.msg_register(list(jtxxlx))
def on_recv_text_msg(wechat_instance: ntchat.WeChat, message):
    msg1=''
    from_wxid=''
    room_wxid=''
    data = message["data"]
    messagetype=message["type"]
    #print("************************")
    #print(messagetype)
    print("---------------------------------------") 
    if "from_wxid" in data:
       from_wxid = data["from_wxid"]
    else:
       from_wxid="为空"
    self_wxid = wechat_instance.get_login_info()["wxid"]
    if "room_wxid" in data:
       room_wxid=data["room_wxid"]
    else:
       room_wxid="为空"
    if "msg"in data:
       msg1=data["msg"]
    else:
       msg1="为空"
    str1="#1"
    str2="01"
    Str3="cyxxsj"
    str4="mytj"
    header = {
        "Accept": "*/*",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Connection": "keep-alive",
        "Content-Type": "application/json",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"
    }
    #print(pattern.search(str))
    #rooms=wechat_instance.get_rooms()
   # print(rooms)
   # mems=wechat_instance.get_room_members(room_wxid="43530777920@chatroom")
    #print(mems)
    # 判断消息不是自己发的，并回复对方
   # if from_wxid =="wxid_6gwykvwvuaaq22":
     #   ceshi= {'msg': 'tom'}
       # r = requests.get('http://localhost:8080/weather/11', params=data)
     #   r.encoding='utf-8'
     #   content1 = r.text
      #  wechat_instance.send_text(to_wxid=from_wxid, content=content1)
      #  wechat_instance.send_text(to_wxid=from_wxid, content="爸爸！")
      #  wechat_instance.send_image(to_wxid=from_wxid,file_path=r"C:\Users\Lenovo\Desktop\59944248e826265c3f8738ef668519d.jpg")
    if str1 in msg1 and room_wxid!="" and room_wxid=="43530777920@chatroom":
        wechat_instance.send_text(to_wxid=room_wxid, content="爸爸！")
    if  room_wxid=="43530777920@chatroom" and from_wxid=="wxid_lbtt6xkksc4k21":
        print()
        #wechat_instance.send_pat(room_wxid=room_wxid,patted_wxid="wxid_lbtt6xkksc4k21")
        #wechat_instance.send_image(to_wxid=room_wxid,file_path=r"C:\Users\Lenovo\Desktop\59944248e826265c3f8738ef668519d.jpg")
    if  room_wxid=="43530777920@chatroom" and from_wxid=="wxid_6gwykvwvuaaq22":        
        r = requests.get(url+'/weather/11', params=data)
        r.encoding='utf-8'
        content1 = r.text
        if str2 in content1:
             wechat_instance.send_text(to_wxid=room_wxid, content=content1)
             wechat_instance.send_room_at_msg(to_wxid=room_wxid, content=content1,at_list= ["wxid_lbtt6xkksc4k21"])
    #判断消息是头发多多发送时，且room_wxid 不为空时，收集群成员信息
    if  Str3 in msg1 and from_wxid=="wxid_uwqszbt8r1qp22" and not room_wxid is None:
       # rooms=wechat_instance.get_rooms()
       # print(rooms)
        mems=wechat_instance.get_room_members(room_wxid=room_wxid)
        request_data ={
         "account": "xxxxxx",
         "sign": "xxxx" }
        print("************************")
        print(mems)
        print("************************")
        print(json.dumps(mems))
        print("************************")
        rsaveOrUpdateMemberList = requests.post(url+"/wechat/saveOrUpdateMemberList", headers = header,data=json.dumps(mems).encode("utf-8"))
        rsaveOrUpdateMemberList.encoding='utf-8'
        saveOrUpdateMemberList = rsaveOrUpdateMemberList.text
        wechat_instance.send_text(to_wxid=room_wxid, content=saveOrUpdateMemberList)
    #如果接收到消息传送至后台进行储存，分析并返回相关数据
    if not room_wxid is None:
        rsaveWechatRoomsInfor = requests.post(url+"/wechat/saveWechatRoomsInfor", headers = header,data=json.dumps(data).encode("utf-8"))
        rsaveWechatRoomsInfor.encoding='utf-8'
        saveWechatRoomsInfor = rsaveWechatRoomsInfor.text
        if not saveWechatRoomsInfor is None :
            if (saveWechatRoomsInfor).endswith(".jpg"):
                 wechat_instance.send_image(to_wxid=room_wxid,file_path=r"C:\Users\Lenovo\Desktop\59944248e826265c3f8738ef668519d.jpg")
            elif saveWechatRoomsInfor.endswith(".mp4"):
                 wechat_instance.send_video(to_wxid=room_wxid,file_path=(saveWechatRoomsInfor))
            elif "excepti" in saveWechatRoomsInfor  :
                 wechat_instance.send_text(to_wxid=room_wxid, content="")
            elif "error" in saveWechatRoomsInfor  :
                 wechat_instance.send_text(to_wxid=room_wxid, content="")            
            else:
                 wechat_instance.send_text(to_wxid=room_wxid, content=saveWechatRoomsInfor)
    #撤回消息重新发送
    if messagetype==11059 and not room_wxid is None :
        resendWechatRoomsInfor = requests.post(url+"/wechat/resendWechatRoomsInfor", headers = header,data=json.dumps(data).encode("utf-8"))
        resendWechatRoomsInfor.encoding='utf-8'
        resendWechatInfor = resendWechatRoomsInfor.text
        if not resendWechatInfor is None :
            print(resendWechatInfor)
            if  resendWechatInfor.endswith("--"):
                  wechat_instance.send_text(to_wxid=room_wxid, content=resendWechatInfor)               
            else:
                 print("消息进来了吗************************")
                 wechat_instance.send_image(to_wxid=room_wxid,file_path=(resendWechatInfor))
    #退群消息通知(为判断该群是否在控制列表内)
    if messagetype==11099 and not room_wxid is None :
          wechat_instance.send_text(to_wxid=room_wxid, content="成员："+str(data["member_list"][0])+"已退群")                               
def test():
 while 1==1:
  time.sleep(10)
  print("111") 
def rabbitmq():
    time.sleep(10)
    credentials = pika.PlainCredentials(mq_username, mq_password)
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(host=mq_host, port=5672, credentials=credentials,virtual_host=mq_vhost)
    )
    channel = connection.channel()

    # 创建一个hello的对列
    channel.queue_declare(queue=mq_queue_name,durable=True)

    # 回调函数，队列中有消息就会触发
    def callback(ch, method, properties, body):
        #print("来自队列：%r" % str(body, encoding='utf8'))
        xxzf=str(body, encoding='utf8')
        aite=str(xxzf[xxzf.find('@|*')+3:])
        print(aite)
        if "@" in xxzf :
          wechat.send_room_at_msg(to_wxid=xxzf[0:xxzf.find('|')], content=xxzf[xxzf.find('|')+1:xxzf.find('@|*')],at_list=[aite] )
        else :
          wechat.send_text(to_wxid=xxzf[0:xxzf.find('|')],content=xxzf[xxzf.find('|')+1:])
        #wechat.send_room_at_msg(to_wxid="43530777920@chatroom", content="@你这是一条测试", at_list=["wxid_6gwykvwvuaaq22"] )
    channel.basic_consume(queue=mq_queue_name, on_message_callback=callback, auto_ack=True)
    print('等待中...')
    channel.start_consuming()
thread1=threading.Thread(target=rabbitmq)
print("执行定是函数查取相关内容")
thread1.start()
try:
    while True:
        pass
except KeyboardInterrupt:
    ntchat.exit_()
    sys.exit()
    
    